﻿/*
 * Created by SharpDevelop.
 * User: Radiation
 * Date: 2017/12/1
 * Time: 19:28
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace autosettime
{
	/// <summary>
	/// 构造时间结构体
	/// </summary>
	[StructLayout(LayoutKind.Sequential)]
    public struct SystemTime
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;
        public ushort wDay;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMiliseconds;
    }
    
    
	/// <summary>
	/// 一些相关的函数
	/// </summary>
	public class functions
	{
		[DllImport("Kernel32.dll")]
		public static extern bool SetLocalTime(ref SystemTime sysTime);
		/// <summary>
		/// 获取网络时间
		/// </summary>
		/// <param name="url">目标http服务器地址</param>
		/// <param name="type">访问方式,http或者https</param>
		/// <returns>服务器时间</returns>
		public string getServerTime(string url,string type="http://")
		{
			string URL = type+url;
			string statusCode;
			try{
				HttpWebRequest req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(URL));
				req.Method = "HEAD";//设置请求方式为请求头，这样就不需要把整个网页下载下来 
				req.Timeout = 10000;
				HttpWebResponse res = (HttpWebResponse)req.GetResponse();
				string result = res.Headers["Date"];
				statusCode = res.StatusCode.ToString();
				if (statusCode == "OK"){
					return result;
				}else{
					return "Error:未知原因";
				}
			}catch (WebException ex){
				return "Error:"+ex.Message;
			}
		}
		
		/// <summary>
		/// 使用windows api来设置系统时间
		/// </summary>
		/// <param name="dt">使用DateTime格式化好的网络时间</param>
		/// <returns></returns>
		public void apiToSetLocalDate(DateTime dt){
			SystemTime sysTime =new SystemTime();
			sysTime.wYear=(ushort)dt.Year;
			sysTime.wMonth=(ushort)dt.Month;
			sysTime.wDay=(ushort)dt.Day;
			sysTime.wHour=(ushort)dt.Hour;
			sysTime.wMinute=(ushort)dt.Minute;
			sysTime.wSecond=(ushort)dt.Second;
			functions.SetLocalTime(ref sysTime);
		}
		
		/// <summary>
		/// 使用Dos命令来设置系统时间
		/// </summary>
		/// <param name="dt">使用DateTime格式化好的网络时间</param>
		/// <returns></returns>
		public void dosToSetLocalDate(DateTime dt){
            Process p = new Process(); 
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "/c date "+dt.ToString("yyyy/M/d H:mm:ss");
            p.StartInfo.UseShellExecute = false;         
            p.StartInfo.RedirectStandardInput = true;  
            p.StartInfo.RedirectStandardOutput = true; 
            p.StartInfo.RedirectStandardError = true;    
            p.StartInfo.CreateNoWindow = true;           
            p.Start(); 
		}
	}
}
